package openapi

import (
	"context"
	"github.com/sashabaranov/go-openai"
)

func Chat(agent string, model string, token string, messages []openai.ChatCompletionMessage) (string, error) {
	// 创建客户端配置
	config := openai.DefaultConfig(token)
	// 设置 DeepSeek 的 API 基础URL
	config.BaseURL = agent

	// 创建客户端
	client := openai.NewClientWithConfig(config)
	resp, err := client.CreateChatCompletion(
		context.Background(),
		openai.ChatCompletionRequest{
			Model:       model,
			Messages:    messages,
			Temperature: 1.3,
			Tools:       make([]openai.Tool, 0),
		},
	)
	if err != nil {
		return "", err
	}
	return resp.Choices[0].Message.Content, nil
}

// ChatStream 流式返回聊天完成内容
func ChatStream(ctx context.Context, agent string, model string, token string, messages []openai.ChatCompletionMessage) (*openai.ChatCompletionStream, error) {
	// 创建客户端配置
	config := openai.DefaultConfig(token)
	// 设置 DeepSeek 的 API 基础URL
	config.BaseURL = agent

	// 创建客户端
	client := openai.NewClientWithConfig(config)

	// 创建流式请求
	stream, err := client.CreateChatCompletionStream(
		ctx,
		openai.ChatCompletionRequest{
			Model:       model,
			Messages:    messages,
			Temperature: 1.3,
			Tools:       make([]openai.Tool, 0),
			Stream:      true,
		},
	)

	if err != nil {
		return nil, err
	}

	return stream, nil
}

// ListModels 获取可用的模型列表
func ListModels(ctx context.Context, pro ModelProperties) ([]openai.Model, error) {
	// 创建客户端配置
	config := openai.DefaultConfig(pro.Token)
	// 设置API基础URL
	config.BaseURL = pro.Agent

	// 创建客户端
	client := openai.NewClientWithConfig(config)

	// 获取模型列表
	modelList, err := client.ListModels(ctx)
	if err != nil {
		return nil, err
	}

	return modelList.Models, nil
}

func ChatStreamWithTool(ctx context.Context, client *openai.Client, model string,
	messages []openai.ChatCompletionMessage, tools []openai.Tool, temperature float64, maxToken int) (*openai.ChatCompletionStream, error) {

	// 创建流式请求
	stream, err := client.CreateChatCompletionStream(
		ctx,
		openai.ChatCompletionRequest{
			Model:       model,
			Messages:    messages,
			Temperature: float32(temperature),
			MaxTokens:   maxToken,
			Tools:       tools,
			Stream:      true,
		},
	)

	if err != nil {
		return nil, err
	}

	return stream, nil
}

func CreateClient(agent string, token string) *openai.Client {
	// 创建客户端配置
	config := openai.DefaultConfig(token)
	// 设置 DeepSeek 的 API 基础URL
	config.BaseURL = agent

	// 创建客户端
	return openai.NewClientWithConfig(config)

}
